package com.mediacloud.app.newsmodule.fragment.imagetext

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.StyleSpan
import android.util.Log
import android.view.*
import android.webkit.*
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.eventTrack.TXReportManager
import com.mediacloud.app.assembly.util.AssetsManager
import com.mediacloud.app.assembly.util.FileUtil
import com.mediacloud.app.assembly.util.StringUtils
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.model.utils.NeedTokenType
import com.mediacloud.app.model.utils.SDKNewsItemJump
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.model.utils.WebViewUtils
import com.mediacloud.app.model.view.WebBrowser
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.HandleDataCollectActivity
import com.mediacloud.app.newsmodule.activity.MagazineDetailActivity
import com.mediacloud.app.newsmodule.activity.WebViewPageActivity
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils
import com.mediacloud.app.newsmodule.model.JSImgItem
import com.mediacloud.app.newsmodule.newsdetail_component.NewsDetailComponentUtils
import com.mediacloud.app.newsmodule.pay.*
import com.mediacloud.app.newsmodule.pay.NormalPayUtil.Others
import com.mediacloud.app.newsmodule.utils.FacadeInvoker
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.utils.WebViewLinkCMSNewsHandle
import com.mediacloud.app.newsmodule.view.BaseSpiderView
import com.mediacloud.app.newsmodule.view.WeatherSetter
import com.mediacloud.app.newsmodule.view.WrapLinearLayout
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.app.user.utils.RxUtils
import io.reactivex.functions.Consumer
import kotlinx.coroutines.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements


fun MagazineDetailFragment.parseHtml(html: String): Job {

    val scope = CoroutineScope(Dispatchers.Default)


    return scope.launch {
        MagazineDetailFragment.iframe_vote_releationship.clear()
        val doc = Jsoup.parse(html)
        val bodyNode: Elements? = doc.getElementsByTag("head")
        if (bodyNode != null && bodyNode.size > 0) {
            bodyNode[0].append("\n<script src=\"file:///android_asset/web/webnews.txt\"/>")
            bodyNode[0].append("\n<script src=\"file:///android_asset/web/webiframe.txt\"/>")
        }
        val imgTags = doc.getElementsByTag("img")
        for (i in 0 until imgTags.size) {
            val imgElement = imgTags[i]
            val imgUrl = imgElement.attr("src")
            if (imgTags.isNullOrEmpty() || imgUrl.contains("tag=1")) { //取消内链新闻的图片点击
                break
            }
            //<img>标签是否在<a>标签里
            val isInATag = (imgElement.parentNode() as Element).tagName() == "a"
            val imgItem = JSImgItem()
            imgItem.info = article.getTitle()
            imgItem.src = imgUrl
            imgItem.hasATag = isInATag
            imgElement.attr("android_imgindex", webImages.size.toString())
            webImages.add(imgItem)
            imgElement.attr("onclick", MagazineDetailFragment.WebImgClick + "(this);")
//                imgElement.attr("onload", "resizeNativeControl(this)")
//                imgElement.attr("onerror", "resizeNativeControl(this)")
        }
        //把h5的音视频给移除了
        val videoNodes = doc.getElementsByTag("video")
        if (videoNodes != null && videoNodes.size > 0) videoNodes.remove()
        val audioNodes = doc.getElementsByTag("audio")
        if (audioNodes != null && audioNodes.size > 0) audioNodes.remove()
        if (webViewInsertHandle != null) {
            webViewInsertHandle.parseHTMLVideoNode(doc)
            webViewInsertHandle.parseHTMLAudioNode(doc)
        }

        //投票的iframe处理验签
        val iframeNodes = doc.getElementsByTag("iframe")

        val key = "act_id"
        var host = null
        iframeNodes.forEach { iframe ->
            if (iframe.hasAttr("morefun") && iframe.hasAttr("src")) {
                iframe.attr("scrolling", "no")
                iframe.attr("frameborder", "no")
                iframe.attr("border", "0")
                iframe.attr("onload", "resizeNativeControl(this)")
                iframe.attr("onresize", "resizeNativeControl(this)")
                val src = iframe.attr("src")
                val iframeId = iframe.attr("id")
                if (URLUtil.isNetworkUrl(src)) {
                    val params: MutableMap<String, String> = WebViewUtils.getUrlParms(src)
                    if (params.containsKey(key) && !TextUtils.isEmpty(params[key])) {
                        MagazineDetailFragment.iframe_vote_releationship[params[key]] =
                            iframeId
                    }
                    /*  try {
                          URL url = new URL(src);
                          if (TextUtils.isEmpty(host))
                              host = url.getHost();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }*/
                }
                iframe.attr("src", src)
            }
        }

        val scriptTag: Elements? = doc.getElementsByTag("script")
        scriptTag?.let {
            if (it.size > 0 && !TextUtils.isEmpty(host)) {//TODO Fix 这里拷贝的以前的逻辑。很明显host一致为null 不会进到里面的。 这里需要排查
                //domain动态替换的
                val domain = "document.domain = '$host';\r\n"
                it[0].append(domain);
            }
        }
        var result = doc.toString()
        if ("1" == activity?.resources?.getString(R.string.use_custom_font)) {
            val fontResId = Utility.getResId(activity, "font", Utility.RAW)
            if (fontResId > 0) {
                try {
                    val fontDes =
                        FileUtil.CACHE + requireContext().packageManager.getPackageInfo(
                            requireContext().packageName,
                            0
                        ).versionName + "font.ttf"
                    if (!FileUtil.isFileEnable(fontDes)) {
                        val success =
                            AssetsManager.copyRawFile2SDCard(activity, fontResId, fontDes)
                        result = result.replace(
                            MagazineDetailFragment.APPFACTORY_CLIENT_LOCAL_FONT_SRC.toRegex(),
                            MagazineDetailFragment.NATIVE_STORAGE_PREFIX + fontDes
                        )
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

        withContext(Dispatchers.Main) {
            if (activity == null) return@withContext
            mWebView.setWebChromeClient(object : WebBrowser.WebChrome(activity, mWebView) {
                override fun onJsConfirm(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    val value = super.onJsConfirm(view, url, message, result)
                    try {
                        webViewInsertHandle?.resizeNativeControl()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                    return value
                }


                override fun onJsAlert(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    val value = super.onJsAlert(view, url, message, result)
                    try {
                        webViewInsertHandle?.resizeNativeControl()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                    return value
                }


                override fun onJsPrompt(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    defaultValue: String?,
                    result: JsPromptResult?
                ): Boolean {
                    val value = super.onJsPrompt(view, url, message, defaultValue, result)
                    try {
                        webViewInsertHandle?.resizeNativeControl()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                    return value
                }
            })
            mWebView.setWebViewClient(object : WebBrowser.WebClient(activity, mWebView) {
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    isLoaded = true
                    if (!isOtherAdded && !isDispose) {
                        isOtherAdded = true
                        if (!isCalendar) {
                            initReadNews()
                            setDisclaimer()
                            zerenbianji()
                            initReward()
                            setKeyWord()
                            setOriginAndReprint()//这里是为了防止接口回来页面还没加载出来的情况
                        }
                        if (mArticleItemReciver != null) { //这里说明取到了详情数据 直接执行下面的流程
                            onDetailNext = false
                            var isEpaper = false
                            if (activity is MagazineDetailActivity) {
                                isEpaper = (activity as MagazineDetailActivity).isEpaper
                            }
//                            if (!isEpaper && !isCalendar) {
//                                addComponent()
//                            }
                        } else {
                            onDetailNext = true
                        }
                    }
                }

                override fun shouldInterceptRequest(
                    view: WebView?,
                    u: String?
                ): WebResourceResponse? {

                    var url = u
                    if (activity != null) {
                        val params: Map<String, String> = WebViewUtils.getUrlParms(url)
                        if (WebViewUtils.judgeDelayLoginParam(
                                activity,
                                NeedTokenType.Delayed,
                                params
                            )
                        ) {
                            if (WebViewUtils.judgeDelayLoginParamAndRefresh(
                                    activity,
                                    NeedTokenType.Delayed,
                                    params
                                )
                            ) {
                                //这个图文的不晓得要改不，先改到起，后续发现不对就注释掉
                                url = mWebView.url
                            }
                            if (!UserInfo.isLogin(activity)) {
                                intoLogin(activity)
                            }
                        }
                    }
                    return super.shouldInterceptRequest(view, url)
                }

                override fun shouldOverrideUrlLoading(view: WebView?, u: String?): Boolean {
                    Log.w("XXX", "shouldOverrideUrlLoading$u")
                    var url = u
                    url = WebViewUtils.replaceDoubleQuesMark(url)
                    val params: MutableMap<String, String> = WebViewUtils.getUrlParms(url)
                    if (WebViewUtils.judgeDelayLoginParam(
                            activity,
                            NeedTokenType.Delayed,
                            params
                        )
                    ) {
                        if (WebViewUtils.judgeDelayLoginParamAndRefresh(
                                activity,
                                NeedTokenType.Delayed,
                                params
                            )
                        ) {
                            //这个图文的不晓得要改不，先改到起，后续发现不对就注释掉
                            url = mWebView.url
                        }
                        if (!UserInfo.isLogin(activity)) {
                            intoLogin(activity)
                        }
                    } else if (!WebViewLinkCMSNewsHandle.handleCMSNews(
                            url,
                            activity,
                            article,
                            catalogItem
                        ) && !SDKNewsItemJump.isMoreFunSDK(activity, url)
                    ) {
                        //  return super.shouldOverrideUrlLoading(view, url);
                        val articleItem = ArticleItem()
                        articleItem.isComment = "0"
                        articleItem.content = "APPTAG"
                        articleItem.isLinkNews = false
                        articleItem.setType(TypeX.NEWS.LINK)
                        articleItem.url = url
                        //暂时不要标题
                        articleItem.title = "  "
                        val needToken = WebViewUtils.getNeedTokenTag(url)
                        val canCollect = false
                        val canShare = true
                        if (catalogItem == null) catalogItem = CatalogItem()
                        val intent = Intent()
                        intent.putExtra(Intent.EXTRA_REFERRER, 1)
                        NewsItemClickUtils.OpenItemNewsHandle(
                            activity,
                            articleItem.getType(),
                            articleItem,
                            catalogItem,
                            intent,
                            needToken,
                            canCollect,
                            canShare
                        )
                    }

                    return true
                }
            })
            result = result.replace(">\\s+<".toRegex(), "><")

            mWebView.loadDataWithBaseURL(
                null,
                HtmlMageZineFormat.getNewContent(result),
                "text/html; charset=utf-8",
                "utf-8",
                null
            )
            mWebView.viewTreeObserver.addOnPreDrawListener(object :
                ViewTreeObserver.OnPreDrawListener {
                var oldHeight = mWebView.measuredHeight
                override fun onPreDraw(): Boolean {
                    if (mWebView.measuredHeight > oldHeight) {
                        closeActivityStateView()
                        webViewInsertHandle.resizeNativeControl()
                        mWebView.viewTreeObserver.removeOnPreDrawListener(this)
                        val childHeight = mScrollView.getChildAt(0).measuredHeight
                        val percent =
                            (mScrollView.scrollY + mScrollView.measuredHeight) * 1f / childHeight
                        if (activity is HandleDataCollectActivity) {
                            (activity as HandleDataCollectActivity?)!!.setScrollProp(percent)
                        }
                    } else {
                        oldHeight = mWebView.measuredHeight
                    }
                    return true
                }
            })

        }
    }

}

object HtmlMageZineFormat {

    fun getNewContent(htmltext: String): String {

        val doc = Jsoup.parse(htmltext)
        val elements = doc.getElementsByTag("img")
        for (element in elements) {
            element.attr("max-width", "100%").attr("height", "auto")
        }

        return doc.toString().replace("margin-top: 15px", "margin-top: 5px")
    }
}

fun MagazineDetailFragment.addComponent() {
    if (!fromShanShiPin && !isFromeVod && mArticleItemReciver.components != null && mArticleItemReciver.components.size > 0) {
        article.mShowSwitch = mShowSwitch
        mRootView.findViewById<ViewStub>(R.id.vsRelate).inflate()

        container = mRootView.findViewById(R.id.relateLayout)

        NewsDetailComponentUtils.addComponentList(
            mRootView.findViewById(R.id.relateLayout),
            mArticleItemReciver.components,
            article,
            activity,
            childFragmentManager,
            1,
            this
        )
        runTask()

//     var scrollView:SmartScrollView?= if(mScrollView is SmartScrollView){mScrollView as SmartScrollView
//     }else {null}
//        DCPTManager.addComponent(mRootView.findViewById(R.id.relateLayout),null,mArticleItemReciver.components,article, childFragmentManager, 1, this)
    }
}

/**
 * 打赏 在网页加载完成后再去设置
 */
fun MagazineDetailFragment.initReward() {
    if ("2" == article.payType) {
        (mRootView.findViewById<View>(R.id.vsReward) as ViewStub).inflate()
        rewardView = mRootView.findViewById(R.id.giveMoney)
        giveMoneyPeople = mRootView.findViewById(R.id.giveMoneyPeople)
        tvRewardTitle = mRootView.findViewById(R.id.giveMoneyTitle)
        rewardView.setOnClickListener(this)
        givenMoneyPeopleListAdapter = GivenMoneyPeopleListAdapter(activity!!)
        giveMoneyPeople.layoutManager =
            ViewUtils.generateRecyclerGridLayoutManager(activity, true, 5)
        giveMoneyPeople.adapter = givenMoneyPeopleListAdapter
        refreshGivenMoneyHead()
    }
}

fun MagazineDetailFragment.refreshGivenMoneyHead() {
    val a = DataInvokeUtil.getZiMeiTiApi().getGivenMoneyPeople(0, article.cps_id).compose(
        TransUtils.fastJSonTransform(
            GivenMoneyResult::class.java
        )
    ).compose(RxUtils.schedulersTransformer())
        .subscribe(Consumer { data ->
            if (activity == null || requireActivity().isFinishing) {
                return@Consumer
            }
            if (isDetached || isDispose() || isRemoving) return@Consumer
            Log.w(MagazineDetailFragment.TAG, "" + data)
            if (data.state) {
                data?.data?.meta?.let {
                    if (it.isNotEmpty()) {
                        giveMoneyPeople.visibility = View.VISIBLE
                        tvRewardTitle.visibility = View.VISIBLE
                        //设置打赏人数
                        val formatStr =
                            "<font color=\"#999999\">-</font> 当前已有 <font color=\"#FF0000\">%s</font> 人打赏文章<font color=\"#999999\"> -</font>"
                        tvRewardTitle.text = Html.fromHtml(String.format(formatStr, it.size))
                        givenMoneyPeopleListAdapter.data.clear()
                        givenMoneyPeopleListAdapter.data.addAll(it)
                        givenMoneyPeopleListAdapter.notifyDataSetChanged()
                    }
                }
            }
        }, Consumer { throwable ->
            if (activity == null || requireActivity().isFinishing) {
                return@Consumer
            }
            if (isDetached || isDispose() || isRemoving) return@Consumer
            Log.w(MagazineDetailFragment.TAG, "" + throwable.message)
        })
}

/**
 * 关键字 在网页加载完成后再去设置
 */
fun MagazineDetailFragment.setKeyWord() {

    if (serverInfo.content_show_keyword == 1 && article.keyword != null && article.keyword.size > 0) {
        mRootView.findViewById<ViewStub>(R.id.vsKeyWord).inflate()
        val layoutKeyWord = mRootView.findViewById<WrapLinearLayout>(R.id.keyContainer);
        for (key in article.keyword) {
            if (!TextUtils.isEmpty(key)) {
                val view = LayoutInflater.from(activity).inflate(R.layout.keyword_item, null)
                val ktv = view.findViewById<TextView>(R.id.ktv)
                ktv.text = key
                layoutKeyWord.addView(ktv)
            }
        }
        if (layoutKeyWord.childCount > 0) {
            layoutKeyWord.visibility = View.VISIBLE
        } else {
            layoutKeyWord.visibility = View.GONE
        }
    }
}

/**
 * 设置新闻标签和来源时间等的布局样式
 */
fun MagazineDetailFragment.setNewsTitle() {
//    tvNewsTitle.text = article.getTitle()
    tvNewsTitle.text =
        if (article.real_title.isNullOrEmpty()) article.getTitle() else article.real_title
    if ("2" == AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.title_align) {
        tvNewsTitle.gravity = Gravity.CENTER
    } else {
        tvNewsTitle.gravity = Gravity.START
    }

    //
    if (!TextUtils.isEmpty(article.subTitle)) {
        text_sub_tile.visibility = View.VISIBLE
        text_sub_tile.text = "──${article.subTitle}"
    } else {
        text_sub_tile.visibility = View.GONE
    }

    if (!TextUtils.isEmpty(magazineAuthor)) {
        magazine_author.visibility = View.VISIBLE
        magazine_author.text = magazineAuthor.trim().replace(",","  ")
    } else {
        magazine_author.visibility = View.GONE
    }

//    if (!TextUtils.isEmpty(article.subTitle) && detailActivity()?.isEpaper!!) {
//        text_sub_tile.visibility = View.VISIBLE
//        text_sub_tile.text = article.subTitle
//    } else {
//        text_sub_tile.visibility = View.GONE
//    //    normalInfoLayout?.setPadding(0, DisplayUtil.dip2px(context, 12f), 0, 0)
//    }




    if ("2" == AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.source_time_align) {
        val layoutNormalInfo: View = mRootView.findViewById(R.id.normalInfoLayout)
        val lp = layoutNormalInfo.layoutParams as LinearLayout.LayoutParams
        lp.gravity = Gravity.CENTER_HORIZONTAL
        layoutNormalInfo.requestLayout()
    }
    //是否显示阅读数 当阅读数接口没有请求成功之前才设置
    initNormalReadView()
    if (!readResponsed) {
        setNormalReadNumber(article.hitCount)
    }
    updateSpiderViewUI()

}

fun MagazineDetailFragment.updateSpiderViewUI() {
    if (article.spider != null) {
        mRootView.findViewById<ViewStub>(R.id.vsSpiderView)?.inflate()
        val spiderView: BaseSpiderView = mRootView.findViewById(R.id.spiderView)
        spiderView.call = this
        spiderView.setDate(article)
        tvSource.visibility = View.GONE
        tvAuthor.visibility = View.GONE
        val showTvAuthor = serverInfo.show_author == 1
        var contentAuthor = article.getAuthor()
        val boldAuthor = serverInfo.show_author_bold == 1
        val colorAuthor = serverInfo.show_author_color
        var isEPaper = false
        if(requireActivity() is MagazineDetailActivity){
            isEPaper = (requireActivity() as MagazineDetailActivity).isEpaper
        }
        if(isEPaper){
            tvAuthor.visibility=View.GONE
            ePagerAuthor.visibility=View.VISIBLE
            showView(true, contentAuthor, false, "#999999", ePagerAuthor,true, requireActivity())
        }else{
            showView(showTvAuthor, contentAuthor, boldAuthor, colorAuthor, tvAuthor,true, requireActivity())
        }
        //原来就默认不显示，不显示则就把该layout隐藏掉
        val showAuthorName = false
        layoutAuthorName.visibility = if (showAuthorName) View.VISIBLE else View.GONE
        showView(
            showAuthorName,
            contentAuthor,
            boldAuthor,
            colorAuthor,
            tvAuthorBottom,
            false,
            requireActivity()
        )

        //是否显示发布日期
        val showTvPublishDate = serverInfo.content_show_publish_date == 1
        val contentPublishDate = article.publishdate_format
        val colorPublishDate = "#FF999999"
        showView(
            showTvPublishDate,
            contentPublishDate,
            false,
            colorPublishDate,
            tvPublishDate,
            false,
            requireActivity()
        )

        //是否显示来源
        val showTvSource = serverInfo.content_show_source == 1
        var contentSource = article.referName
        if (contentSource.isNullOrEmpty()) {
            tvSource.visibility = View.GONE
            // contentSource = requireContext().resources.getString(R.string.app_name)
        } else {
            val boldSource = serverInfo.show_source_bold == 1
            val colorSource = serverInfo.show_source_color
            if(isEPaper){
                tvSource.visibility=View.GONE
                ePagerSource.visibility=View.VISIBLE
                //电子报来源颜色写死
                showView(
                    true,
                    contentSource,
                    false,
                    "#222222",
                    ePagerSource,
                    false,
                    requireActivity()
                )
            }else{
                showView(
                    showTvSource,
                    contentSource,
                    boldSource,
                    colorSource,
                    tvSource,
                    false,
                    requireActivity()
                )
            }


        }
    } else {
        var isEPaper = false
        if(requireActivity() is MagazineDetailActivity){
            isEPaper = (requireActivity() as MagazineDetailActivity).isEpaper
        }
        //是否显示来源
        val showTvSource = serverInfo.content_show_source == 1
        var contentSource = article.referName
        if (TextUtils.isEmpty(contentSource)) {
            tvSource.visibility = View.GONE
            // contentSource = requireContext().resources.getString(R.string.app_name)
        } else {
            val boldSource = serverInfo.show_source_bold == 1
            val colorSource = serverInfo.show_source_color
            if(isEPaper){
                //电子报来源颜色写死
                tvSource.visibility=View.GONE
                ePagerSource.visibility=View.VISIBLE
                //产品说报刊来源不受开关配置，默认显示
                showView(
                    true,
                    contentSource,
                    false,
                    "#222222",
                    ePagerSource,
                    false,
                    requireActivity()
                )
            }else{
            showView(
                showTvSource,
                contentSource,
                boldSource,
                colorSource,
                tvSource,
                false,
                requireActivity()
            )
            }
        }


        //是否显示作者
        val showTvAuthor = serverInfo.show_author == 1
        val contentAuthor = article.getAuthor()
        val boldAuthor = serverInfo.show_author_bold == 1
        val colorAuthor = serverInfo.show_author_color

        if(isEPaper){
            tvAuthor.visibility=View.GONE
            ePagerAuthor.visibility=View.VISIBLE
            showView(true, contentAuthor, false, "#999999", ePagerAuthor,true, requireActivity())
        }else{
            showView(showTvAuthor, contentAuthor, boldAuthor, colorAuthor, tvAuthor,true, requireActivity())
        }
        //是否显示发布日期
        val showTvPublishDate = serverInfo.content_show_publish_date == 1
        val contentPublishDate = article.publishdate_format
        val boldPublishDate = serverInfo.show_publish_date_bold == 1
        val colorPublishDate = serverInfo.show_publish_date_color
        showView(
            showTvPublishDate,
            contentPublishDate,
            boldPublishDate,
            colorPublishDate,
            tvPublishDate,
            false,
            requireActivity()
        )

        if (!showTvSource && tvAuthor.visibility == View.VISIBLE) {
            val lp = tvPublishDate.layoutParams as ConstraintLayout.LayoutParams
            lp.topToBottom = R.id.authorName
            tvPublishDate.requestLayout()
        }

        if (!showTvPublishDate) {
            //不显示日期时，显示一排，跟iOS保持一致
            val lp = tvReadNumber.layoutParams as ConstraintLayout.LayoutParams
            if (tvAuthor.visibility == View.VISIBLE) {
                lp.startToEnd = R.id.authorName
                lp.topToTop = R.id.authorName
            } else {
                if (showTvSource) {
                    lp.startToEnd = R.id.mNewsSource
                    lp.topToTop = R.id.mNewsSource
                }
            }
            tvReadNumber.requestLayout()
        }


    }
}

/**
 *  初始化 阅读数控件
 */
fun MagazineDetailFragment.initNormalReadView() {
    if (article.showreadingcountflag == 1 && serverInfo.content_show_hit_count == 1) {
        tvReadNumber.visibility = View.VISIBLE
        var bold = serverInfo.show_hit_count_bold == 1
        var color = serverInfo.show_hit_count_color
        if (article.spider != null) {
            color = "#FF999999"
            bold = false
        }
        // tvReadNumber.text = "0"
        if (!TextUtils.isEmpty(color)) {
            tvReadNumber.setTextColor(Color.parseColor(color))
        }
        if (bold) tvReadNumber.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
    } else {
        tvReadNumber.visibility = View.GONE
    }
}

fun MagazineDetailFragment.setNormalReadNumber(number: Long) {
    val content = if (article.spider != null) {
        "浏览量 ${StringUtils.toTenThousand(number)}"
    } else {
        //number.toString() + "浏览"
        "浏览量 ${StringUtils.toTenThousand(number)}"
    }
    article.hitCount=number
    if (article.refreshHitCount()) {
        FacadeInvoker.postDelay(false)
    }
    tvReadNumber.text = content
}

/**
 * 免责声明 在网页加载完成后再去设置
 */
fun MagazineDetailFragment.setDisclaimer() {
    if (serverInfo.content_show_disclaimer == 1 && article.disclaimer != null && !fromMicroLive) {
        var name = article.disclaimer.name
        val value = article.disclaimer.value
        if (!TextUtils.isEmpty(value)) {
            if (TextUtils.isEmpty(name)) {
                name = getString(R.string.disclaimer)
            }
            val style = SpannableStringBuilder("$name:$value")
            style.setSpan(
                StyleSpan(Typeface.BOLD),
                0,
                name.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            val mDisclaimer = mRootView.findViewById<TextView>(R.id.mDisclaimer)
            mDisclaimer.visibility = View.VISIBLE
            mDisclaimer.text = value
        }
    }
}

/**
 * 责任编辑 在网页加载完成后再去设置
 */
fun MagazineDetailFragment.zerenbianji() {
    //是否显示责任编辑
    val showTvEditor =
        serverInfo.content_show_responsible_editor == 1 && !fromMicroLive && !TextUtils.isEmpty(
            article.zerenbianji
        )
    val contentEditor = getString(R.string.dutyEdit) + article.zerenbianji
    val boldEditor = serverInfo.show_responsible_editor_bold == 1
    val colorEditor = serverInfo.show_responsible_editor_color
    showView(
        showTvEditor,
        contentEditor,
        boldEditor,
        colorEditor,
        mRootView.findViewById(R.id.mDuty),
        false,
        requireActivity()
    )
}

fun MagazineDetailFragment.initWeatherView() {
    if (serverInfo.show_weather == 1) {
        mRootView.findViewById<ViewStub>(R.id.vsWeatherView).inflate()
        if (weatherSetter == null) {
            weatherSetter = WeatherSetter(mRootView.findViewById(R.id.weatherView))
        }
    }
}

private fun showView(
    show: Boolean,
    content: String?,
    bold: Boolean,
    color: String?,
    textView: TextView?,
    isAuthor: Boolean,
    activity: Activity?
) {
    if (show && !TextUtils.isEmpty(content)) {

        textView?.visibility = View.VISIBLE
//        if (isAuthor && (activity as MagazineDetailActivity).isEpaper) {
//            textView!!.text = "记者："
//        }
        if (!textView!!.text.contains(content!!)) {
            textView.append(content)
        }
        if (!TextUtils.isEmpty(color)) textView?.setTextColor(Color.parseColor(color))
        if (bold) textView?.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
    } else {
        textView?.visibility = View.GONE
    }
}


fun MagazineDetailActivity.initPayView() {
    findViewById<ViewStub>(R.id.vsPayView).inflate()
    tvPayTips = findViewById(R.id.tv_pay_tips)
    paySeeMoreLayout = findViewById(R.id.pay_see_more_layout)
    playHowMuch = findViewById(R.id.pay_how_much)
    tvVipPayHowMuch = findViewById(R.id.tv_vip_pay_how_much)

    normalPayUtil = NormalPayUtil(this, catalogItem, object : Others {
        override fun getVipPayView(): TextView {
            return tvVipPayHowMuch
        }

        override fun operation(): String {
            return getString(R.string.pay_buy_article)
        }

        override fun payView(): MutableList<View>? {
            val payView: MutableList<View> = ArrayList()
            payView.add(paySeeMoreLayout)
            return payView
        }

        override fun paidView(): MutableList<View>? {
            return null
        }

        override fun openView(): TextView {
            return if (isMember) {
                tvVipPayHowMuch
            } else playHowMuch
        }
    }, object : PaidContentListener {
        override fun onPaidContent(meta: PaidMetas) {
            imageTextDetailFragment.updateBuyContent(meta)
            imageTextDetailFragment.showHTMLData(meta.content)
        }
    }, false, this)
}

fun MagazineDetailFragment.detailActivity(): MagazineDetailActivity? {
    val activity = requireActivity()
    return if (activity is MagazineDetailActivity) {
        activity
    } else {
        null
    }
}


/**
 * 查看原文点击及禁止转载显示与否
 * @receiver MagazineDetailFragment
 */
fun MagazineDetailFragment.setOriginAndReprint() {
    if (activity?.isFinishing == true || activity?.isDestroyed == true) {
        return
    }
    article.extension?.let {
        if (it.originalFlag == 0) {//非原创
            originalLabel.visibility = View.GONE
        } else {
            originalLabel.visibility = View.VISIBLE
        }
        if (!TextUtils.isEmpty(it.originalLinkUrl)) {
            tvOriginal.visibility = View.VISIBLE
            tvOriginal.setOnClickListener {
                WebViewPageActivity.start(
                    "",
                    article.extension.originalLinkUrl,
                    activity
                )
            }
        } else {
            tvOriginal.visibility = View.GONE
        }
        if (it.reprintFlag == 0) {
            tvReprint.visibility = View.VISIBLE
        } else {
            tvReprint.visibility = View.GONE
        }
        if ((activity is MagazineDetailActivity) && (activity as MagazineDetailActivity).isEpaper) {
            tvReprint.visibility = View.GONE
        }

        bottomLine.visibility = View.VISIBLE
    }

}